import * as chitu from 'maishu-chitu';
import { urlParams } from '../common';
import { ImageService, Service as BaseService } from "maishu-services-sdk";
import { CookieValueStore, IService, ServiceConstructor } from "maishu-chitu-service";
import { errorHandle } from 'mobile/error-handle';

let protocol = location.protocol;
export interface LoginInfo {
    token: string;
    userId: string;
}
export abstract class Service extends BaseService {
    static token = new chitu.ValueStore<string>(getCookie("token"));

    // static get token() {
    //     return getCookie("token");
    // }
    // static set token(value: string) {
    //     setCookie("token", value, 365);
    // }

    static createInstance<T extends IService>(type?: ServiceConstructor<T>): T {
        let service = new type();
        //TODO: 处理错误
        service.error.add((sender, error) => {
            // alert({ title: "错误", message: error.message });
            errorHandle(error)
        })

        return service;
    }

    async ajax<T>(url: string, options: chitu.AjaxOptions) {

        if (!url.startsWith("http")) {
            let host = location.host;
            let pathname = location.pathname

            if (!pathname.endsWith("/")) {
                // pathname = pathname + "/";
                let arr = pathname.split("/");
                arr[arr.length - 1] = "";
                pathname = arr.join("/");
            }

            if (url.startsWith("/")) {
                url = `${protocol}//${host}${url}`;
            }
            else {
                url = `${protocol}//${host}${pathname}${url}`;
            }
        }

        console.log(url);

        options = options || {};
        options.headers = options.headers || {};


        if (this.applicationId)
            options.headers['application-id'] = this.applicationId;

        // if (urlParams.token) {
        //     options.headers['token'] = urlParams.token;
        // }
        // else if (Service.token.value != null && Service.token.value != null) {
        //     options.headers['token'] = Service.token.value;
        // }

        return super.ajax<T>(url, options);
    }

    static get storeName() {
        return "";
    }

    get protocol() {
        return location.protocol
    }

    get applicationId() {
        return urlParams.appKey;
    }

    static get appToken() {
        return urlParams.token;
    }
}



export function imageUrl(path: string, width?: number, height?: number) {
    let imageService = new ImageService();
    return imageService.imageSource(path, width, height);
}

Service.token.add((value) => {
    setCookie("token", value, 365);
})

function getCookie(name: string) {
    if (typeof document == 'undefined')
        return null;

    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function setCookie(name: string, value: string, days?: number) {
    value = value || "";

    // nodejs 没有 document
    if (typeof document == 'undefined')
        return;

    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
